// router/index.js
import {createRouter, createWebHistory} from 'vue-router'

const authRoutes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('@/components/accounts/auth/UserLogin.vue'),
        meta: {requiresAuth: false, guestOnly: true, title: '川塔 | 登录'}
    },
    {
        path: '/register',
        name: 'register',
        component: () => import('@/components/accounts/auth/UserRegister.vue'),
        meta: {requiresAuth: false, guestOnly: true, title: '川塔 | 注册'},
    },
    {
        path: '/forgot_password',
        name: 'passwordForgot',
        component: () => import('@/components/accounts/auth/ForgotPassword.vue'),
        meta: {requiresAuth: false, guestOnly: true, title: '川塔 | 忘记密码'}
    },
    {
        path: '/auth-redirect/',
        name: 'AuthLogin',
        component: () => import('@/components/accounts/auth/OauthLogin.vue'),
        meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 授权登录'},
        children: [
            {
                path: 'gitee',
                name: 'giteeLogin',
                component: () => import('@/components/accounts/auth/OauthLogin.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | gitee授权登录'}
            },
            {
                path: 'github',
                name: 'githubLogin',
                component: () => import('@/components/accounts/auth/OauthLogin.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | github授权登录'}
            },
            {
                path: 'qq',
                name: 'qqLogin',
                component: () => import('@/components/accounts/auth/OauthLogin.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | QQ授权登录'}
            },
            {
                path: 'weibo',
                name: 'weiboLogin',
                component: () => import('@/components/accounts/auth/OauthLogin.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 微博授权登录'}
            }
        ]
    },
    {
        path: '/callback/',
        name: 'AuthCallback',
        component: () => import('@/components/accounts/auth/SocialCallback.vue'),
        meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 授权回调'},
        children: [
            {
                path: 'gitee',
                name: 'giteeCallback',
                component: () => import('@/components/accounts/auth/SocialCallback.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | gitee授权回调'}
            },
            {
                path: 'github',
                name: 'githubCallback',
                component: () => import('@/components/accounts/auth/SocialCallback.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | github授权回调'}
            },
            {
                path: 'qq',
                name: 'qqCallback',
                component: () => import('@/components/accounts/auth/SocialCallback.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | QQ授权回调'}
            },
            {
                path: 'weibo',
                name: 'weiboCallback',
                component: () => import('@/components/accounts/auth/SocialCallback.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 微博授权回调'}
            },
        ]
    },
]
const userRoutes = [
    {
        path: '/personal',
        name: 'personal',
        component: () => import('@/views/user/PersonalCenterPage.vue'),
        meta: {requiresAuth: true, guestOnly: false, title: '川塔 | 个人中心'},
    },
    {
        path: '/edit',
        name: 'profileEdit',
        component: () => import('@/views/user/ProfileEditPage.vue'),
        meta: {requiresAuth: true, guestOnly: false, title: '川塔 | 编辑资料'},
        children: [
            {
                path: 'basic',
                name: 'editBasic',
                component: () => import('@/components/accounts/personal/ProfileEditBasic.vue'),
                meta: {requiresAuth: true, guestOnly: false, title: '川塔 | 编辑基本资料'},
            },
            {
                path: 'social',
                name: 'editSocial',
                component: () => import('@/components/accounts/personal/ProfileEditSocial.vue'),
                meta: {requiresAuth: true, guestOnly: false, title: '川塔 | 编辑社交资料'},
            },
            {
                path: 'password',
                name: 'editPassword',
                component: () => import('@/components/accounts/personal/PasswordEdit.vue'),
                meta: {requiresAuth: true, guestOnly: false, title: '川塔 | 编辑密码'},
            },
            {
                path: '',
                name: 'editDefault',
                redirect: {name: 'editBasic'}
            }
        ],
    },
    {
        path: '/notification',
        name: 'notification',
        component: () => import('@/views/user/NotificationCenterPage.vue'),
        meta: {requiresAuth: true, guestOnly: false, title: '川塔 | 通知中心'},
    },
    {
        name: 'admin-articles',
        path: '/admin-articles',
        component: () => import('@/views/user/ArticlesManagementPage.vue'),
        meta: {requiresAuth: true, guestOnly: false, title: '川塔 | 个人文章管理'},
        children: [
            {
                path: 'create',
                name: 'create-article',
                component: () => import('@/components/articles/personal/CreateArticle.vue'),
                meta: {requiresAuth: true, guestOnly: false, title: '川塔 | 创建个人文章'},
            },
            {
                path: 'edit/:id',
                name: 'edit-article',
                component: () => import('@/components/articles/personal/EditArticle.vue'),
                meta: {requiresAuth: true, guestOnly: false, titleTemplate: '川塔 | 编辑个人文章-{{title}}'},
            },
            {
                path: 'show/:id',
                name: 'show-article',
                component: () => import('@/components/articles/personal/ShowArticle.vue'),
                meta: {requiresAuth: true, guestOnly: false, titleTemplate: '川塔 | 个人文章-{{title}}'},
            },
            {
                path: '',
                name: 'list-articles',
                component: () => import('@/components/articles/personal/ListArticle.vue'),
                meta: {requiresAuth: true, guestOnly: false, title: '川塔 | 个人文章列表'},
            },
        ]
    },
]
const detailRoutes = [
    {
        path: '/subject/:id',
        name: 'subject-detail',
        component: () => import('@/views/detail/SubjectDetailPage.vue'),
        meta: {requiresAuth: false, guestOnly: false, titleTemplate: '分类-{{title}}'}
    },
    {
        path: '/tags',
        name: 'tags',
        component: () => import('@/views/detail/TagsPage.vue'),
        meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 标签列表'},
    },
    {
        path: '/tags/:id',
        name: 'tag-detail',
        component: () => import('@/views/detail/TagDetailPage.vue'),
        meta: {requiresAuth: false, guestOnly: false, titleTemplate: '标签 - {{title}}'}
    },
    {
        path: '/article/:id',
        name: 'article-detail',
        component: () => import('@/views/detail/ArticleDetailPage.vue'),
        meta: {requiresAuth: false, guestOnly: false, titleTemplate: '文章 - {{title}}'}
    },
    {
        path: '/search',
        name: 'search',
        component: () => import('@/views/detail/SearchPage.vue'),
        meta: {requiresAuth: false, guestOnly: false, titleTemplate: '搜索 - {{title}}'}
    },

]
const commonRoutes = [
    {
        path: '/',
        name: 'home',
        component: () => import('@/views/base/HomePage.vue'),
        meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 首页'}
    },
    {
        path: '/subject',
        name: 'article',
        component: () => import('@/views/base/ArticleSubjectPage.vue'),
        meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 文章专题'}
    },
    {
        path: '/archive',
        name: 'archive',
        component: () => import('@/views/base/ArchivePage.vue'),
        meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 文章归档'}
    },
    {
        path: '/resource',
        name: 'resource',
        component: () => import('@/views/base/ResourcePage.vue'),
        children: [
            {
                path: 'download',
                name: 'download',
                component: () => import('@/components/resources/ResourceDownload.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 资源下载'}
            },
            {
                path: 'navigation',
                name: 'navigation',
                component: () => import('@/components/resources/ResourceNavigation.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 网址导航'},
            },
            {
                path: 'tools',
                name: 'tools',
                component: () => import('@/components/resources/ResourceTools.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 工具箱'},
            },
            {
                path: '',
                name: 'resource-default',
                redirect: {name: 'download'}
            }
        ]
    },
    {
        path: '/about',
        name: 'about',
        component: () => import('@/views/base/AboutPage.vue'),
        children: [
            {
                path: 'friendlinks',
                name: 'friendlinks',
                component: () => import('@/components/about/AboutFriendLinks.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 友情链接'},
            },
            {
                path: 'introduce',
                name: 'introduce',
                component: () => import('@/components/about/AboutSection.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 本站介绍'}
            },
            {
                path: 'message',
                name: 'message',
                component: () => import('@/components/about/AboutMessage.vue'),
                meta: {requiresAuth: false, guestOnly: false, title: '川塔 | 留言墙'}
            },
            {
                path: '',
                name: 'about-default',
                redirect: {name: 'introduce'}
            }
        ]
    },
]
// 动态导入工具文件夹中的所有组件
const toolRoutes = []

const modules = import.meta.glob('@/components/resources/tools/*.vue')
for (const path in modules) {
    const fileName = path.split('/').pop()
    const componentName = fileName.replace(/\.vue$/, '').toLowerCase()
    const routeName = componentName.replace(/^tool-/, '')
    const componentTitle = routeName.replace(/-/g, ' ')

    toolRoutes.push({
        path: `/resource/tools/${routeName}`,
        name: `tools-${routeName}`,
        component: modules[path],
        meta: {requiresAuth: false, guestOnly: false, title: `川塔-工具 | ${componentTitle}`}
    })
}



// 合并路由配置
const routes = [
    ...authRoutes,
    ...userRoutes,
    ...detailRoutes,
    ...toolRoutes,
    ...commonRoutes
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 在路由配置之后添加导航守卫
// 限制未登录用户访问特定页面

router.beforeEach((to, from, next) => {
    const isAuth = !!localStorage.getItem('authToken')

    // Guest Only 页面已登录时重定向
    if (to.meta.guestOnly && isAuth) return next('/')

    // 需要认证且未登录时重定向
    if (to.meta.requiresAuth && !isAuth) {
        return next({
            path: '/login',
            query: {redirect: to.fullPath} // 记录原始路径
        })
    }
    // 记录原始路径
    if (to.path !== '/login') {
        sessionStorage.setItem('referrer', from.path)
    }
    next()
})


router.afterEach((to) => {
    let baseTitle = to.meta.title || '川塔'

    // 检查是否使用 titleTemplate 并替换相应的参数
    if (to.meta.titleTemplate) {
        const template = to.meta.titleTemplate
        if (to.query.title) { // 使用 query 参数而不是 params 参数
            baseTitle = template.replace('{{title}}', to.query.title)
        }
    }

    document.title = baseTitle
})

export default router
